package com.lry.rpc.starter.bean;

import com.lry.rpc.starter.annotation.RpcService;
import com.lry.util.StringUtils;
import lombok.Data;

@Data
public class ServiceConfig<T> {
    protected String version;
    protected String group;
    protected Integer weight;
    protected T ref;
    protected String interfaceName;
    protected String serviceImplName;
    protected Class<?> interfaceClass;
    protected String token;

    public ServiceConfig(Class<?> implClazz) {

        RpcService rpcService = implClazz.getAnnotation(RpcService.class);
        if(null!=rpcService.interfaceClass()){
            this.interfaceClass = rpcService.interfaceClass();
            this.interfaceName = this.interfaceClass.getName();
        }
        if(this.interfaceClass.equals(void.class)){
            this.interfaceClass = implClazz.getInterfaces()[0];
            this.interfaceName = this.interfaceClass.getName();
        }
        this.serviceImplName = rpcService.serviceImplName();

        try {
            this.ref = (T) implClazz.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        this.version = rpcService.version();
        this.group = rpcService.group();
        this.weight = rpcService.weight();
        this.token = rpcService.token();
    }

    public void setToken(String token){
        if(StringUtils.isBlank(this.token)){
            this.token = token;
        }
    }

    public void setWeight(Integer weight){
        if(null==this.weight){
            this.weight = weight;
        }
    }

    public T get(){
        return ref;
    }
}
